package com.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.annotation.FootPrint;
import com.mall.annotation.SearchAnnotation;
import com.mall.db.domain.*;
import com.mall.db.service.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 页面跳转控制器
 */
@Controller
@RequestMapping(("/page"))
public class PageController {

    @Value("${email.times}")
    private long emailTimes;

    @Resource(name = "schedulerService")
    private SchedulerService ss;

    @Resource(name = "memberService")
    private MemberService ms;

    @Resource(name = "configService")
    private ConfigService cs;

    @Resource(name = "roleService")
    private RoleService ros;

    @Resource(name = "categoryService")
    private CategoryService cgs;

    @Resource(name = "keywordService")
    private KeywordService ks;

    @Resource(name = "noticeService")
    private NoticeService ns;

    @Resource(name = "brandService")
    private BrandService bs;

    @Resource(name = "goodsService")
    private GoodsService gs;

    @Resource(name = "orderService")
    private OrderService os;

    @Resource(name = "addressService")
    private AddressService as;

    @Resource(name = "commentService")
    private CommentService cms;

    /*
     *
     *
     * */

    @RequestMapping("/taoTao")
    public String taoTao(){
        return "/views/userShoppingI/taoTao";
    }

    @RequestMapping("/system/ps")
    public String index(ModelMap mmap, HttpServletRequest req){
        HttpSession session = req.getSession();
        Member m = (Member) session.getAttribute("member");
        mmap.addAttribute("m",m);
        return "/views/index";
    }

    @RequestMapping("/login")
    public String login(){
        return "/views/login";
    }

    @RequestMapping("/forgetPwd")
    public String forgetPwd(){
        return "/views/forgetPwd";
    }



    @RequestMapping("/forgetNext")
    public String forgetNext(@RequestParam(name = "email") String email,
                             ModelMap mmap){
        mmap.addAttribute("email",email);
        return "/views/forgetNext";
    }

    @RequestMapping("/forgetVerify")
    public String forgetVerify(@RequestParam(name = "code") String code,
                               @RequestParam(name = "token") String token,
                               ModelMap mmap,
                               HttpServletResponse res,
                               HttpSession session){
        try {

            BASE64Decoder decoder = new BASE64Decoder();
            code = new String(decoder.decodeBuffer(code), "utf-8");
            token = new String(decoder.decodeBuffer(token), "utf-8");

            //判断时间的有效性
            if (System.currentTimeMillis()-Long.parseLong(code) > emailTimes){
                mmap.addAttribute("tips","邮件链接已过期，请重新获取！");

                return "/views/tips";
            }
            if (!StringUtils.isEmpty(token)){
                QueryWrapper<Member> qw = new QueryWrapper<>();
                qw.eq("email",token);
                Member m = ms.getOne(qw);
                if (m!=null){
                    mmap.addAttribute("id",m.getId());
                    mmap.addAttribute("email",token);

                    code = (new Random().nextInt(999)+1000) +"";
                    session.setAttribute("mobileCode",code);
                    mmap.addAttribute("code",code);
                    return "/views/pwdEdit";
                }else {
                    mmap.addAttribute("tips","该邮箱不存在或已被注册！");

                    return "/views/tips";
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        mmap.addAttribute("tips","密码找回失败！");
        return "/views/tips";
    }

    @RequestMapping("/pwdEdit")
    public String pwdEdit(){
        return "/views/pwdEdit";
    }


    @RequestMapping("/main")
    public String main(){
        return "/views/main";
    }



    @RequestMapping("/{root}/{pageName}")
    public String createPageLink(@PathVariable(name = "root") String root,
                                 @PathVariable(name = "pageName") String page,
                                 ModelMap mmap,HttpServletRequest req){
        HttpSession session = req.getSession();
        Member m = (Member) session.getAttribute("member");
        mmap.addAttribute("m",m);
        return String.format("/views/%s/%s",root,page);
    }

    @RequestMapping("/system/memberEdit/{id}")
    public String createPageUpdate(@PathVariable(name = "id") int id, ModelMap mmp){
        mmp.addAttribute("m",ms.getById(id));
        return String.format("/views/system/memberEdit");
    }

    @RequestMapping("/system/map/{lng}/{lat}")
    public String map(@PathVariable(name = "lng") Double lng,
                      @PathVariable(name = "lat") Double lat,
                      ModelMap mmp){
        //TODO 获取改用户登录时，所在的城市信息 （经纬度）
        lng = lng == 0.0?108.281113:lng;
        lat = lat == 0.0?22.869252:lat;

        mmp.addAttribute("lng",lng);
        mmp.addAttribute("lat",lat);
        return "/views/system/map";
    }


    @RequestMapping("/goods/goodsEdit/{id}")
    public String goodsUpdate(@PathVariable(name = "id") int id, ModelMap mmp){
        QueryWrapper<Brand> qw1 = new QueryWrapper<>();
        List<Brand> list1 = new ArrayList<>();
        list1 = bs.list(qw1);
        qw1.eq("id",gs.getById(id).getBrandId());
        Brand bra1 = bs.getOne(qw1);
        mmp.addAttribute("list",list1);
        mmp.addAttribute("g",gs.getById(id));
        mmp.addAttribute("b",bra1);

        QueryWrapper<Category> qw2 = new QueryWrapper<>();
        List<Category> list2 = new ArrayList<>();
        list2 = cgs.list(qw2);
        qw2.eq("id",gs.getById(id).getCategoryId());
        Category cg = cgs.getOne(qw2);
        mmp.addAttribute("list2",list2);
        mmp.addAttribute("c",cg);




        return String.format("/views/goods/goodsEdit");
    }

    @RequestMapping("/mallManagement/brandEdit/{id}")
    public String brandUpdate(@PathVariable(name = "id") int id, ModelMap mmp){
        mmp.addAttribute("b",bs.getById(id));
        return String.format("/views/mallManagement/brandEdit");
    }


    //编辑定时任务
    @RequestMapping("/system/editQuartz/{jobName}")
    public String editQuartz(@PathVariable(value = "jobName") String jobName,ModelMap mmp){

        mmp.addAttribute("s",ss.getByJobName(jobName));

        return String.format("/views/system/editQuartz");
    }

    @RequestMapping("/system/config/{page}")
    public String configPage(@PathVariable(name = "page") String page,ModelMap mmp){
        mmp.addAttribute("c",cs.getById(1));
        return String.format("/views/system/%s",page);
    }

    @RequestMapping("/system/userVipEdit/{id}")
    public String createUpdate(@PathVariable(name = "id") int id, ModelMap mmp){
        mmp.addAttribute("m",ms.getById(id));
        return String.format("/views/system/userVipEdit");
    }

    @RequestMapping("/system/roleEdit/{id}")
    public String configPage(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("r",ros.getById(id));
        return "/views/system/roleEdit";
    }

    @RequestMapping("/mallManagement/categoryEdit/{id}")
    public String categoryEdit(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("c",cgs.getById(id));
        return "/views/mallManagement/categoryEdit";
    }

    @RequestMapping("/goods/keywordEdit/{id}")
    public String EditKeyword(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("ks",ks.getById(id));
        return String.format("/views/goods/keywordEdit");
    }

    @RequestMapping("/goods/noticeEdit/{id}")
    public String noticeEdit(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("ns",ns.getById(id));
        return String.format("/views/goods/noticeEdit");
    }

    @RequestMapping("/order/orderLook/{id}")
    public String orderEdit(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("os",os.getById(id));
        return String.format("/views/order/orderLook");
    }

    @RequestMapping("/order/orderGo/{id}")
    public String orderGo(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("os",os.getById(id));
        return String.format("/views/order/orderGo");
    }

    @RequestMapping("/order/orderBack/{id}")
    public String orderBack(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("os",os.getById(id));
        return String.format("/views/order/orderBack");
    }

    @RequestMapping("/order/orderGet/{id}")
    public String orderGet(@PathVariable(name = "id") int id,ModelMap mmp){
        mmp.addAttribute("os",os.getById(id));
        return String.format("/views/order/orderGet");
    }

    //userindex页面搜索后传类目id至main界面
    @RequestMapping("/userIndex/UserMain/{cid}/{mid}")
    @SearchAnnotation  //记录cid和mid
    public String UserMainGoods(@PathVariable(name="cid") int cid,//参数列表 cid和mid位置不能交换
                                @PathVariable(name = "mid") int mid,
                                ModelMap mmp){
        mmp.addAttribute("cid",cid);
        return "/views/userIndex/UserMain";
    }

    //点击商品简介可以跳转到商品详细页
    @RequestMapping("/userIndex/goodDetail/{gid}")
    @FootPrint  //记录mid和gid
    public String UserGoodDetail(@PathVariable(name = "gid") int gid, ModelMap mmp){
        Goods goods = gs.getById(gid);
        mmp.addAttribute("g",goods);
        return "/views/userIndex/GoodDetail";
    }

    @RequestMapping("/userIndex/OrderAdd/{mid}/{gid}")
    public String UserOrderAdd(@PathVariable(name = "mid") int mid,
                               @PathVariable(name = "gid") int gid,
                               ModelMap mmp){
        //拿地址
        QueryWrapper<Address> qw = new QueryWrapper();
        qw.eq("mid",mid);
        qw.eq("default_check",0);
        List<Address> list = as.list(qw);
        mmp.addAttribute("a", list.get(0));

        //拿商品信息
        Goods goods = gs.getById(gid);
        mmp.addAttribute("g", goods);

        //拿用户信息
        Member member = ms.getById(mid);
        mmp.addAttribute("m", member);
        return "/views/userIndex/OrderAdd";
    }
}
